

package com.example.singing.view;

import com.example.singing.manager.CompetitionManager;
import com.example.singing.manager.ScoreManager;
import com.example.singing.manager.TeamManager;
import com.example.singing.model.Competition;
import com.example.singing.model.Score;
import com.example.singing.model.Team;
import com.example.singing.model.User;
import com.example.singing.util.AlertUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 历史查询界面
 */
public class HistoryView {
    private VBox view;
    private CompetitionManager competitionManager;
    private TeamManager teamManager;
    private ScoreManager scoreManager;
    private VBox scoresContainer; // 用于展示所有评分项的容器
    private User currentUser; // 当前用户

    // 保留无参构造函数以兼容旧代码
    public HistoryView() {
        this.currentUser = null;
        this.competitionManager = new CompetitionManager();
        this.teamManager = new TeamManager();
        this.scoreManager = new ScoreManager();
        createView();
    }

    // 带用户参数的构造函数
    public HistoryView(User user) {
        this.currentUser = user;
        this.competitionManager = new CompetitionManager();
        this.teamManager = new TeamManager();
        this.scoreManager = new ScoreManager();
        createView();
    }

    /**
     * 创建历史查询界面
     */
    private void createView() {
        VBox historyView = new VBox(20);
        historyView.setPadding(new Insets(20));

        Label title = new Label("历史评分查询");
        title.setStyle("-fx-font-size: 20px; -fx-font-weight: bold; -fx-text-fill: #673ab7;");

        // 在初始化时清理无效的评分数据
        System.out.println("初始化历史查询界面，开始清理无效数据...");
        scoreManager.cleanInvalidScores(teamManager, competitionManager);

        // 筛选条件
        HBox filterBox = new HBox(15);
        filterBox.setAlignment(javafx.geometry.Pos.CENTER_LEFT);

        ComboBox<Competition> competitionFilter = new ComboBox<>();
        ObservableList<Competition> competitions = FXCollections.observableArrayList(competitionManager.getAllCompetitions());
        // 创建一个特殊的"所有赛事"项
        Competition allCompetition = new Competition("ALL", "所有赛事", "", "", "");
        competitions.add(0, allCompetition); // 添加到列表开头
        competitionFilter.setItems(competitions);
        competitionFilter.setPromptText("选择比赛");
        competitionFilter.setPrefWidth(200);

        ComboBox<Team> teamFilter = new ComboBox<>();
        ObservableList<Team> teams = FXCollections.observableArrayList(teamManager.getAllTeams());
        // 创建一个特殊的"所有队伍"项
        Team allTeam = new Team("ALL", "所有队伍", new ArrayList<>(), "");
        teams.add(0, allTeam); // 添加到列表开头
        teamFilter.setItems(teams);
        teamFilter.setPromptText("选择队伍");
        teamFilter.setPrefWidth(200);

        Button filterBtn = new Button("筛选");
        filterBtn.setStyle("-fx-background-color: #673ab7; -fx-text-fill: white;");
        filterBtn.setOnAction(e -> applyFilters(competitionFilter.getValue(), teamFilter.getValue()));

        Button resetBtn = new Button("重置");
        resetBtn.setStyle("-fx-background-color: #9e9e9e; -fx-text-fill: white;");
        resetBtn.setOnAction(e -> {
            competitionFilter.setValue(null);
            teamFilter.setValue(null);
            displayScores(scoreManager.getAllScores());
        });

        filterBox.getChildren().addAll(
                new Label("比赛:"), competitionFilter,
                new Label("队伍:"), teamFilter,
                filterBtn, resetBtn
        );

        // 评分展示容器
        scoresContainer = new VBox(15);
        scoresContainer.setPadding(new Insets(10));
        // 设置初始显示
        displayScores(scoreManager.getAllScores());

        // 添加滚动条
        ScrollPane scrollPane = new ScrollPane(scoresContainer);
        scrollPane.setFitToWidth(true);
        scrollPane.setPrefHeight(600);

        historyView.getChildren().addAll(title, filterBox, scrollPane);
        this.view = historyView;
    }

    /**
     * 显示评分列表（非表格式）
     */
    private void displayScores(List<Score> scores) {
        scoresContainer.getChildren().clear();
        
        // 在显示评分前先清理无效数据
        scoreManager.cleanInvalidScores(teamManager, competitionManager);
        
        if (scores.isEmpty()) {
            Label emptyLabel = new Label("暂无评分记录");
            emptyLabel.setStyle("-fx-font-size: 16px; -fx-text-fill: #9e9e9e;");
            emptyLabel.setPadding(new Insets(50, 0, 50, 0));
            emptyLabel.setAlignment(Pos.CENTER);
            scoresContainer.setAlignment(Pos.CENTER);
            scoresContainer.getChildren().add(emptyLabel);
        } else {
            scoresContainer.setAlignment(Pos.TOP_LEFT);
            // 重新获取评分列表，确保已清理无效数据
            List<Score> validScores = scoreManager.getAllScores();
            
            if (validScores.isEmpty()) {
                Label emptyLabel = new Label("暂无有效评分记录");
                emptyLabel.setStyle("-fx-font-size: 16px; -fx-text-fill: #9e9e9e;");
                emptyLabel.setPadding(new Insets(50, 0, 50, 0));
                emptyLabel.setAlignment(Pos.CENTER);
                scoresContainer.setAlignment(Pos.CENTER);
                scoresContainer.getChildren().add(emptyLabel);
            } else {
                for (Score score : validScores) {
                    // 获取关联的比赛和队伍信息
                    Competition competition = competitionManager.getCompetitionById(score.getCompetitionId());
                    Team team = teamManager.getTeamById(score.getTeamId());
                    
                    if (competition != null && team != null) {
                        scoresContainer.getChildren().add(createScoreItem(competition, team, score));
                    } else {
                        // 如果比赛或队伍不存在，创建一个错误提示的评分项
                        VBox errorItem = new VBox(10);
                        errorItem.setPadding(new Insets(15));
                        errorItem.setStyle("-fx-background-color: #ffebee; -fx-background-radius: 10; -fx-border-color: #ef5350; -fx-border-width: 1px;");
                        
                        Label errorTitle = new Label("评分记录 (数据不完整)");
                        errorTitle.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #c62828;");
                        
                        Label scoreInfo = new Label("评分ID: " + score.getId() + ", 最终得分: " + String.format("%.1f", score.getFinalScore()));
                        scoreInfo.setStyle("-fx-font-size: 13px; -fx-text-fill: #666;");
                        
                        Label errorInfo = new Label();
                        errorInfo.setStyle("-fx-font-size: 13px; -fx-text-fill: #ef5350;");
                        
                        if (competition == null && team == null) {
                            errorInfo.setText("错误: 找不到关联的比赛(ID: " + score.getCompetitionId() + ")和队伍(ID: " + score.getTeamId() + ")");
                        } else if (competition == null) {
                            errorInfo.setText("错误: 找不到关联的比赛(ID: " + score.getCompetitionId() + ")");
                        } else {
                            errorInfo.setText("错误: 找不到关联的队伍(ID: " + score.getTeamId() + ")");
                        }
                        
                        // 如果是管理员，显示删除按钮
                        if (currentUser != null && "管理员".equals(currentUser.getRole())) {
                            Button deleteButton = new Button("删除");
                            deleteButton.setStyle("-fx-background-color: #f44336; -fx-text-fill: white;");
                            deleteButton.setOnAction(e -> {
                                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                                alert.setTitle("确认删除");
                                alert.setHeaderText(null);
                                alert.setContentText("确定要删除这条不完整的评分记录吗？");
                                
                                alert.showAndWait().ifPresent(response -> {
                                    if (response == ButtonType.OK) {
                                        System.out.println("确认删除无效评分ID: " + score.getId());
                                        boolean deleted = scoreManager.deleteScoreById(score.getId());
                                        if (deleted) {
                                            System.out.println("无效评分删除成功，刷新界面");
                                            AlertUtil.showInfoAlert("成功", "评分记录已删除");
                                            displayScores(scoreManager.getAllScores());
                                        } else {
                                            System.err.println("无效评分删除失败");
                                            AlertUtil.showErrorAlert("错误", "删除失败，请重试");
                                        }
                                    }
                                });
                            });
                            
                            errorItem.getChildren().addAll(errorTitle, scoreInfo, errorInfo, deleteButton);
                        } else {
                            errorItem.getChildren().addAll(errorTitle, scoreInfo, errorInfo);
                        }
                        
                        scoresContainer.getChildren().add(errorItem);
                    }
                }
            }
        }
    }

    /**
     * 创建单个评分项的显示组件
     */
    private VBox createScoreItem(Competition competition, Team team, Score score) {
        VBox scoreItem = new VBox(10);
        scoreItem.setPadding(new Insets(15));
        scoreItem.setStyle("-fx-background-color: white; -fx-background-radius: 10; -fx-effect: dropshadow(gaussian, rgba(0,0,0,0.1), 10, 0, 0, 5);");
        
        // 头部信息：评分ID和评分时间
        HBox headerBox = new HBox(10);
        headerBox.setAlignment(Pos.CENTER_LEFT);
        headerBox.setHgrow(new Region(), Priority.ALWAYS); // 使右侧空间可拉伸
        Label idLabel = new Label("评分ID: " + score.getId());
        idLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666;");
        headerBox.getChildren().add(idLabel);
        
        // 如果是管理员，显示删除按钮
        if (currentUser != null && "管理员".equals(currentUser.getRole())) {
            Button deleteButton = new Button("删除");
            deleteButton.setStyle("-fx-background-color: #f44336; -fx-text-fill: white;");
            deleteButton.setOnAction(e -> {
                // 显示确认对话框
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setTitle("确认删除");
                alert.setHeaderText(null);
                alert.setContentText("确定要删除这条评分记录吗？");
                
                alert.showAndWait().ifPresent(response -> {
                    if (response == ButtonType.OK) {
                        // 执行删除操作
                        System.out.println("确认删除评分ID: " + score.getId());
                        boolean deleted = scoreManager.deleteScoreById(score.getId());
                        if (deleted) {
                            System.out.println("评分删除成功，刷新界面");
                            AlertUtil.showInfoAlert("成功", "评分记录已删除");
                            // 重新获取最新的评分数据并刷新界面
                            List<Score> updatedScores = scoreManager.getAllScores();
                            System.out.println("删除后重新获取评分数据，总数: " + updatedScores.size());
                            displayScores(updatedScores);
                        } else {
                            System.err.println("评分删除失败");
                            AlertUtil.showErrorAlert("错误", "删除失败，请重试");
                        }
                    }
                });
            });
            
            // 将删除按钮放在右侧
            HBox.setHgrow(deleteButton, Priority.NEVER);
            headerBox.getChildren().add(deleteButton);
        }
        
        // 比赛和队伍信息区域
        HBox infoBox = new HBox(20);
        infoBox.setAlignment(Pos.CENTER_LEFT);
        
        // 比赛信息
        VBox competitionBox = new VBox(5);
        competitionBox.setAlignment(Pos.CENTER);
        
        // 比赛图片
        ImageView competitionImage = new ImageView();
        competitionImage.setFitWidth(80);
        competitionImage.setFitHeight(50);
        competitionImage.setPreserveRatio(true);
        competitionImage.setStyle("-fx-border-radius: 5px; -fx-background-color: #f5f5f5;");
        
        if (competition.getBackgroundImagePath() != null && !competition.getBackgroundImagePath().isEmpty()) {
            File file = new File(competition.getBackgroundImagePath());
            if (file.exists()) {
                competitionImage.setImage(new Image(file.toURI().toString()));
            } else {
                // 设置默认比赛图像
                competitionImage.setImage(getDefaultImage("competition"));
            }
        } else {
            competitionImage.setImage(getDefaultImage("competition"));
        }
        
        Label competitionName = new Label(competition.getName());
        competitionName.setStyle("-fx-font-weight: bold; -fx-text-fill: #333;");
        competitionName.setMaxWidth(120);
        competitionName.setAlignment(Pos.CENTER);
        competitionName.setWrapText(true);
        
        competitionBox.getChildren().addAll(competitionImage, competitionName);
        
        // 队伍信息
        VBox teamBox = new VBox(5);
        teamBox.setAlignment(Pos.CENTER);
        
        // 队伍图片
        ImageView teamImage = new ImageView();
        teamImage.setFitWidth(80);
        teamImage.setFitHeight(80);
        teamImage.setPreserveRatio(true);
        teamImage.setStyle("-fx-border-radius: 5px; -fx-background-color: #f5f5f5;");
        
        if (team.getPhotoPath() != null && !team.getPhotoPath().isEmpty()) {
            File file = new File(team.getPhotoPath());
            if (file.exists()) {
                teamImage.setImage(new Image(file.toURI().toString()));
            } else {
                // 设置默认队伍图像
                teamImage.setImage(getDefaultImage("team"));
            }
        } else {
            teamImage.setImage(getDefaultImage("team"));
        }
        
        Label teamName = new Label(team.getName());
        teamName.setStyle("-fx-font-weight: bold; -fx-text-fill: #333;");
        teamName.setMaxWidth(120);
        teamName.setAlignment(Pos.CENTER);
        teamName.setWrapText(true);
        
        teamBox.getChildren().addAll(teamImage, teamName);
        
        // 评分信息
        VBox scoreBox = new VBox(10);
        scoreBox.setPadding(new Insets(0, 0, 0, 20));
        scoreBox.setPrefWidth(400);
        
        Label scoreTitle = new Label("评委评分");
        scoreTitle.setStyle("-fx-font-size: 14px; -fx-font-weight: bold; -fx-text-fill: #673ab7;");
        
        HBox judgeScoresBox = new HBox(10);
        judgeScoresBox.setPadding(new Insets(5, 0, 5, 0));
        
        // 显示每个评委的评分（保留一位小数）
        int judgeIndex = 1;
        for (Double judgeScore : score.getJudgeScores()) {
            Label judgeScoreLabel = new Label("评委 " + judgeIndex + ": " + String.format("%.1f", judgeScore));
            judgeScoreLabel.setStyle("-fx-font-size: 13px; -fx-text-fill: #666;");
            judgeScoresBox.getChildren().add(judgeScoreLabel);
            judgeIndex++;
        }
        
        // 最终得分
        HBox finalScoreBox = new HBox(10);
        Label finalScoreLabel = new Label("最终得分: ");
        finalScoreLabel.setStyle("-fx-font-size: 16px; -fx-font-weight: bold; -fx-text-fill: #333;");
        
        Label scoreValueLabel = new Label(String.format("%.1f", score.getFinalScore()));
        scoreValueLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold; -fx-text-fill: #673ab7;");
        
        finalScoreBox.getChildren().addAll(finalScoreLabel, scoreValueLabel);
        finalScoreBox.setAlignment(Pos.CENTER_LEFT);
        
        scoreBox.getChildren().addAll(scoreTitle, judgeScoresBox, finalScoreBox);
        
        infoBox.getChildren().addAll(competitionBox, teamBox, scoreBox);
        
        scoreItem.getChildren().addAll(headerBox, infoBox);
        
        return scoreItem;
    }

    /**
     * 获取默认图像
     */
    private Image getDefaultImage(String type) {
        // 确保SVG格式正确编码并避免特殊字符问题
        try {
            if ("competition".equals(type)) {
                // 为比赛创建一个简单的默认矩形图像
                StringBuilder svgBuilder = new StringBuilder();
                svgBuilder.append("<svg xmlns='http://www.w3.org/2000/svg' width='80' height='50'>");
                svgBuilder.append("<rect width='80' height='50' fill='%23e0e0e0' rx='5'/>");
                svgBuilder.append("<text x='40' y='30' font-family='Arial' font-size='12' text-anchor='middle' fill='%239e9e9e'>比赛</text>");
                svgBuilder.append("</svg>");
                String svg = svgBuilder.toString();
                
                // 显式编码特殊字符
                String encodedSvg = svg.replace("%", "%25")
                                      .replace("<", "%3C")
                                      .replace(">", "%3E")
                                      .replace("&", "%26");
                
                return new Image("data:image/svg+xml;charset=utf-8," + encodedSvg);
            } else if ("team".equals(type)) {
                // 为队伍创建一个简单的默认圆形图像
                StringBuilder svgBuilder = new StringBuilder();
                svgBuilder.append("<svg xmlns='http://www.w3.org/2000/svg' width='80' height='80'>");
                svgBuilder.append("<circle cx='40' cy='40' r='38' fill='%23e0e0e0'/>");
                svgBuilder.append("<text x='40' y='48' font-family='Arial' font-size='14' text-anchor='middle' fill='%239e9e9e'>队伍</text>");
                svgBuilder.append("</svg>");
                String svg = svgBuilder.toString();
                
                // 显式编码特殊字符
                String encodedSvg = svg.replace("%", "%25")
                                      .replace("<", "%3C")
                                      .replace(">", "%3E")
                                      .replace("&", "%26");
                
                return new Image("data:image/svg+xml;charset=utf-8," + encodedSvg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 应用筛选条件
     */
    private void applyFilters(Competition selectedComp, Team selectedTeam) {
        List<Score> filteredScores = scoreManager.getAllScores().stream()
                .filter(score -> {
                    boolean matchComp = selectedComp == null || "ALL".equals(selectedComp.getId()) || score.getCompetitionId().equals(selectedComp.getId());
                    boolean matchTeam = selectedTeam == null || "ALL".equals(selectedTeam.getId()) || score.getTeamId().equals(selectedTeam.getId());
                    return matchComp && matchTeam;
                })
                .collect(Collectors.toList());

        displayScores(filteredScores);
    }

    /**
     * 获取界面视图
     */
    public VBox getView() {
        return view;
    }
}